import { Injectable } from '@nestjs/common';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Menu } from './entities/menu.entity';
import { Result } from 'src/utils/result';

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu)
    private readonly sysMenuEntity: Repository<Menu>,
  ) {}

  async create(createMenuDto: CreateMenuDto) {
    await this.sysMenuEntity.save(createMenuDto);
    return Result.success();
  }

  async findAll() {
    const res = await this.sysMenuEntity.find();
    return Result.success(res);
  }

  async findOne(id: number) {
    const res = await this.sysMenuEntity.findOne({
      where: {
        menuId: id,
      },
    });
    return Result.success(res);
  }

  async update(id: number, updateMenuDto: UpdateMenuDto) {
    await this.sysMenuEntity.update(id, updateMenuDto);
    return Result.success();
  }

  async remove(menuId: number) {
    const ids = await this.findDeleteIds(menuId);
    await this.sysMenuEntity.delete(ids);
    return Result.success();
  }

  async findDeleteIds(menuId: number, ids: number[] = []) {
    if (ids.length === 0) ids.push(menuId);
    const findMenus = await this.sysMenuEntity.find({
      where: {
        parentId: menuId,
      },
      select: ['menuId'],
    });

    if (findMenus.length > 0) {
      for (let index = 0; index < findMenus.length; index++) {
        const i = findMenus[index];
        ids.push(i.menuId);
        await this.findDeleteIds(i.menuId, ids);
      }
    }
    return ids;
  }
}
